package de.duester.genealogy;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class StartScreenActivity extends Activity implements OnItemClickListener {
	private ListView lvOptions;

	private final int RC_NEW_FAMILY_TREE = 0;
	private final int RC_LOAD_FAMILY_TREE = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start_screen);
		init();
	}

	private void init() {
		Utility.context = getApplicationContext();

		lvOptions = (ListView) findViewById(R.id.lvOptions);
		lvOptions.setAdapter(new OptionsAdapter(this,
				android.R.layout.simple_list_item_1, new String[] {
						getString(R.string.txtNewFamilyTree),
						getString(R.string.txtLoadFamilyTree) }));
		lvOptions.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		switch (position) {
		case 0:
			Intent intent = new Intent(this, NewFamilyTreeActivity.class);
			startActivityForResult(intent, RC_NEW_FAMILY_TREE);
			break;
		case 1:
			intent = new Intent(this, LoadFamilyTreeActivity.class);
			startActivityForResult(intent, RC_LOAD_FAMILY_TREE);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			Utility.openDB(data.getStringExtra("dbName"));
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
		}
	}

	private class OptionsAdapter extends ArrayAdapter<String> {
		private int textViewResourceId;
		private String[] data;

		public OptionsAdapter(Context context, int textViewResourceId, String[] data) {
			super(context, textViewResourceId, data);
			this.textViewResourceId = textViewResourceId;
			this.data = data;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = null;

			if (convertView == null) {
				LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
				v = li.inflate(textViewResourceId, null);
				v.setBackgroundResource(R.drawable.start_menu_element);
			} else
				v = convertView;

			TextView tv = (TextView) v.findViewById(android.R.id.text1);
			tv.setText(data[position]);

			return v;
		}
	}

}
